package com.qtummatrix.service.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Gongshiyong
 * Date 2019-10-16 17:21
 */

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // servletRequest 和 servletResponse 转为 HttpServletRequest、HttpServletResponse
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        HttpSession session = httpServletRequest.getSession();

        // 如果为 true，用户登录过
        if (session.getAttribute("user") != null) {

            // 放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);

        } else {
            httpServletResponse.sendRedirect("login.jsp");
        }

    }

    @Override
    public void destroy() {

    }
}
